package wenjun.du.androidart.viewcreate

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.android.synthetic.main.activity_view_size.*
import wenjun.du.androidart.R

/**
 * 正确获取控件宽高的方法
 *
 * 不管是在activity生命周期的哪个方法中，都不能获取view测量的大小
 *
 * 1.onWindowFocusChanged 表示window绘制 显示完成，可以获取控件宽高
 * 2.viewTree 监听
 * 3.view.post方法回调
 * 4.view.measure() 方法不常用
 *
 * */
class ViewSizeActivity : AppCompatActivity() {
    companion object {
        private const val TAG = "ViewSizeActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_view_size)
        // 方式 1 只会调用一次
        view_target.post {
            //view绘制成功后 会执行post调用
            Log.d(
                TAG,
                "onCreate() called target measuredWidth: ${view_target.measuredWidth} width: ${view_target.width} "
            )
        }
        //方式 2  可能会多次调用
        view_target.viewTreeObserver.addOnGlobalLayoutListener {
            //布局树的全局监听
            Log.d(
                TAG,
                "addOnGlobalLayoutListener() called target measuredWidth: ${view_target.measuredWidth} width: ${view_target.width} "
            )
        }
    }

    /**
     * 生命周期的onResume方法中，顶层的view(DecorView)还没开始绘制
     * 所以此时是拿不到控件的宽高值的
     *
     * */
    override fun onResume() {
        super.onResume()
        Log.d(
            TAG,
            "onResume() called target measuredWidth: ${view_target.measuredWidth} width: ${view_target.width}"
        )
    }

    /**
     * 测量值和最终值一般来说是相等的
     * 可能会多次调用
     *
     * */
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        Log.d(
            TAG,
            "onWindowFocusChanged() called with: hasFocus = $hasFocus target measuredWidth: ${view_target.measuredWidth} width: ${view_target.width}"
        )
    }


}